<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8'>
    <title>01 - OL4加载天地图WMTS服务展示地图</title>
    <!--    <script src="../lib/ol4/ol4.js"></script>-->
    <script src='../lib/ol6.4.3/ol.js'></script>
    <script src='../lib/proj4/proj4.js'></script>
    <script src='https://cdn.jsdelivr.net/npm/js-base64@3.7.5/base64.min.js'></script>
    <link rel='stylesheet' href='../css/ol4/ol.css'>
    <link rel='stylesheet' href='../css/main.css'>
</head>
<body>
<div id='map'></div>
</body>
<script>
	const projection = ol.proj.get('EPSG:4326');
	console.log(projection);
	projection.setExtent([-180, -90, 180, 90]);
	const tileSize = 256;
	const projectionExtent = projection.getExtent();
	const origins = [
		[-180.0, 90.0],
		ol.extent.getTopLeft(projectionExtent),
	];
	const origin = origins[1];
	console.log('extent:', projectionExtent);
	console.log('origin:', origin);

	let style = new ol.style.Style({
		image: new ol.style.Icon({
			src: '',
			// 图标锚点
			anchor: [0.75, 0.5],
		}),
	});

	console.log(style.getImage().getPixelRatio());

	const size = ol.extent.getWidth(projectionExtent) / tileSize;

	const resolutions = new Array(18);
	const matrixIds = new Array(18);
	for (let z = 1; z < 21; z++) {
		resolutions[z] = size / Math.pow(2, z);
		matrixIds[z] = z;
	}
	console.log(resolutions);

	const tileGrid = new ol.tilegrid.WMTS({
		origin,
		resolutions: resolutions,
		extent: projectionExtent,
		matrixIds: matrixIds,
	});

	// const url = `http://120.52.31.31:590/service/api/egis/base/v1/wmts`;
	const url = `http://120.52.31.31:590/service/api/egis/base/v1/wrts/getTile?level={z}&x={x}&y={y}`;

	const opts = {
		username: '28524d8c65844630a3427270c9a16323',
		password: '84bc17650bb04491aa8475b9cbe3d1c4',
	};

	const xyzSource = new ol.source.XYZ({
		url,
		projection,
		wrapX: false,
		tileLoadFunction: (imageTile, src) => {
			const xhr = new XMLHttpRequest();
			xhr.onloadstart = function () {
				xhr.responseType = 'blob';
			};
			xhr.addEventListener('loadend', function (evt) {
				const data = this.response;
				if (data !== undefined) {
					imageTile.getImage().src = URL.createObjectURL(data);
					imageTile.getImage().onload = function () {
						URL.revokeObjectURL(this.src);
					};
				} else {
					// eslint-disable-next-line no-undef
					imageTile.setState(ol.TileState.ERROR);
				}
			});
			xhr.addEventListener('error', function () {
				// eslint-disable-next-line no-undef
				imageTile.setState(ol.TileState.ERROR);
			});
			xhr.open('GET', src);
			// xhr.setRequestHeader('Authorization', `Basic ${Base64.encode(`${opts.username}:${opts.password}`)}`);
			xhr.setRequestHeader('Authorization', `Basic Mjg1MjRkOGM2NTg0NDYzMGEzNDI3MjcwYzlhMTYzMjM6ODRiYzE3NjUwYmIwNDQ5MWFhODQ3NWI5Y2JlM2QxYzQ=`);
			if (opts.accessToken) {
				xhr.setRequestHeader('access_token', opts.accessToken);
			}
			xhr.send();
		},
	});
	// 图层
	const baseLayer = new ol.layer.Tile({
		source: xyzSource,
	});

	// const circlePoint = ol.proj.transform([116.384722, 39.889916], 'EPSG:4326', 'EPSG:4490');
	const points = [
		[0, 0],
		[-111.35, 69],
		[110.998735, 30.818967],
		[116.384722, 39.889916],
		[119.97154785156252, 30.40197483062744],
		[105.855593, 32.427233],
		[120.282129049117, 30.392968655169],
		[118.738208, 32.010466],
	];
	const centerPoint = points[1];

	const iconFeature = new ol.Feature({
		geometry: new ol.geom.Point(centerPoint),
	});

	const iconStyle = new ol.style.Style({
		image: new ol.style.Icon({
			anchor: [10, 26],
			anchorXUnits: 'pixels',
			anchorYUnits: 'pixels',
			src: '../image/gis_rydw.gif',
		}),
	});

	iconFeature.setStyle(iconStyle);

	const vectorSource = new ol.source.Vector({
		features: [iconFeature],
		wrapX: false,
	});

	const iconLayer = new ol.layer.Vector({
		source: vectorSource,
	});

	const map = new ol.Map({
		layers: [
			baseLayer,
			// baseLayer1,
			iconLayer,
		],
		target: 'map',
		view: new ol.View({
			center: centerPoint,
			projection,
			zoom: 7,
			maxZoom: 21,
			minZoom: 1,
			resolutions,
		}),
		controls: ol.control.defaults().extend([
			new ol.control.MousePosition(),
		]),
	});

	// const metersPerUnit = map.getView().getProjection().getMetersPerUnit();
	//
	// const realRadius = radius / metersPerUnit;
	//
	// const circleFeature = new ol.Feature({
	//     geometry: new ol.geom.Circle(centerPoint, realRadius)
	// });

	map.on('pointermove', evt => {
		if (evt.dragging) return;
		let hit = map.hasFeatureAtPixel(map.getEventPixel(evt.originalEvent));
		map.getTargetElement().style.cursor = hit ? 'pointer' : 'default';
		// console.log(hit);
	});

</script>
</html>
